package wec_wallet.ebo.com.activity;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Switch;
import android.widget.TextView;

import com.google.gson.Gson;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import bassproject.ebo.com.ebobass.activity.MyBaseActivity;
import bassproject.ebo.com.ebobass.http_utils.interfaces.IHttpPostListener;
import bassproject.ebo.com.ebobass.http_utils.utils.Ipost;
import bassproject.ebo.com.ebobass.utils.IToast;
import bassproject.ebo.com.ebobass.utils.I_Share;
import bassproject.ebo.com.ebobass.utils.Lg;
import butterknife.BindString;
import butterknife.BindView;
import butterknife.BindViews;
import butterknife.ButterKnife;
import butterknife.OnClick;
import wec_wallet.ebo.com.R;
import wec_wallet.ebo.com.adapter.InterceptAdapter;
import wec_wallet.ebo.com.bean.InterceptBean;
import wec_wallet.ebo.com.bean.InterceptDataBean;
import wec_wallet.ebo.com.common.Constant;
import wec_wallet.ebo.com.common.SharedPreference;
import wec_wallet.ebo.com.util.PermissionsChecker;
import wec_wallet.ebo.com.utils.Functions;

/**
 * 智能诈骗拦截主界面
 * Created by Administrator on 2018/3/9.
 */

public class InterceptActivity extends MyBaseActivity {
    @BindView(R.id.lv_intercept)
    public ListView lv;

    @BindView(R.id.btn_intercept)
    public Button btn_intercept;

    @BindViews({R.id.tv_title, R.id.tv_interceptTime, R.id.tv_intercept_more, R.id
            .tv_intercept_state})
    public List<TextView> tvList;

    InterceptAdapter adapter;
    @BindView(R.id.actionbar_back)

    RelativeLayout re_back;
    @BindView(R.id.switch_intercept)

    Switch aSwitch;
    String time;

    @BindString(R.string.safety)
    String title;

    @BindString(R.string.already_open)
    String open;

    @BindString(R.string.unopened)
    String close;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_intercept);
        ButterKnife.bind(this);
        initView();
    }

    @Override
    public void initViews() {

    }

    private void initView() {
        tvList.get(0).setText(title);
        boolean isOpen = SharedPreference.getIsOpenIntercept(getApplicationContext(), I_Share
                .readAccountUserid());
        if (isOpen) {
            tvList.get(3).setText(open);
            aSwitch.setChecked(true);
        } else {
            tvList.get(3).setText(close);
            aSwitch.setChecked(false);
        }
        aSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                boolean isopen = b;
                if (b) {
                    String[] primissions = {Manifest.permission.READ_PHONE_STATE};
                    if (PermissionsChecker.lacksPermissions(InterceptActivity.this, primissions)) {
                        PermissionsChecker.showMissingPermissionDialog(InterceptActivity.this,
                                2002, getString(R.string.help), getString(R.string
                                        .string_help_text), primissions);
                        aSwitch.setChecked(false);
                        isopen = false;
                    } else {
                        tvList.get(3).setText(open);
                    }
                } else {
                    tvList.get(3).setText(close);
                }
                SharedPreference.putOpenIntercept(getApplicationContext(), I_Share
                        .readAccountUserid(), isopen);

            }
        });
        lv.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                switch (motionEvent.getAction()) {
                    case MotionEvent.ACTION_MOVE:
                        return true;
                    default:
                        break;
                }
                return true;
            }
        });

//        getData();
    }

    private void getData() {

        Map<String, Object> map = new HashMap<>();
        map.put("limit", "10");
        map.put("order_by", "1");
        map.put("page", "1");
        map.put("sort_field", "updated_at");
        map.put("token", I_Share.readAccountToken());
        map.put("uid", I_Share.readAccountUserid());
        Functions.post(InterceptActivity.this, Constant.URL_BLACKLIST, map, new
                ListenerBlackList(), false, true);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 2002:
                aSwitch.setChecked(true);
                tvList.get(3).setText(open);
                break;
        }
    }

    @Override
    public void onClick(View v) {

    }

    private List<InterceptDataBean> getInterceptData(String json) {
        return new Gson().fromJson(json, InterceptBean.class).getData();

    }

    @OnClick({R.id.actionbar_back, R.id.btn_intercept, R.id.tv_intercept_more})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.actionbar_back:
                finish();
                break;
            case R.id.btn_intercept:
                startActivity(new Intent(getApplicationContext(), ReportActivity.class));
                break;
            case R.id.tv_intercept_more:
                startActivity(new Intent(getApplicationContext(), BlackListActivity.class));
                break;

        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        getData();
    }

    private class ListenerBlackList implements IHttpPostListener {
        @Override
        public void onTimeOut() {

        }

        @Override
        public void responseSuccess(String result) {
            if (Ipost.isTimeOut(result)) {
                return;
            }
            if (null != result) {
                try {

                    JSONObject resultObject = new JSONObject(result);
                    String status = resultObject.getString("error");
                    time = resultObject.getString("last_time");
                    tvList.get(1).setText(time);
                    if (resultObject.has("is_auth") && resultObject.getString("is_auth").equals
                            ("0")) {
                        IToast.show(resultObject.getString("error_msg"));
                        Functions.relogin(InterceptActivity.this);//登录过期
                        return;
                    }
                    if (resultObject.has("error_msg")) {
                        IToast.show(resultObject.getString("error_msg"));
                        return;
                    }
                    if (status.equals("0")) {
                        List<InterceptDataBean> list = new ArrayList<>();
                        list.clear();
                        list = getInterceptData(result);

                        adapter = new InterceptAdapter(getApplicationContext(), list);
                        lv.setAdapter(adapter);
                        if (list.size() > 0) {
                            tvList.get(2).setVisibility(View.VISIBLE);
                        } else {
                            tvList.get(2).setVisibility(View.GONE);
                        }
                    }

                } catch (Exception e) {
                    // TODO: handle exception
//                    IToast.show(e.toString());
                    Lg.d(getClass() + ",接口解析异常：\n" + e.toString());
                }
            } else {
                Lg.d("黑名单列表 result=null");

            }
        }
    }
}
